<template>
  <Pages :current="1" :tab="false">
    <view class="page-header">
      <text class="header-title">图片管理</text>
      <CustomButton text="创建图片" backgroundColor="#409eff" />
    </view>

    <!-- 触发按钮 -->
    <button @click="showMediaPicker">选择媒体文件</button>

    <!-- 自定义弹窗 -->
    <media-picker ref="mediaPicker" @select="handleFileSelect" />

    <scroll-view class="tags-list" scroll-y :style="{ height: '90vh' }" @refresherrefresh="handleRefresh"
      refresher-enabled :refresher-triggered="refreshing">

      <view v-if="tags.length === 0" class="empty-state">
        <text class="empty-text">暂无图片</text>
      </view>

      <view v-else class="tags-content">
        <view v-for="tag in tags" :key="tag.id" class="tag-item">
          <view class="tag-image">
            <image :src="tag.path" mode="aspectFill" />
          </view>
          <view class="tag-actions">
            <CustomButton text="编辑" @click="handleEditTag(tag)" backgroundColor="#67c23a" />
            <CustomButton text="删除" @click="handleDeleteTag(tag)" backgroundColor="#f56c6c" />
          </view>
        </view>
      </view>
    </scroll-view>
    <!-- <TagForm v-if="showForm" :tag="currentTag" @submit="handleSubmitTag" @cancel="handleCancelForm" /> -->
  </Pages>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useTagStore } from '@/stores/tags'
import { useDatabase } from './hooks/useDatabase'
import CustomButton from '@/components/CustomButton.vue'
import Pages from '@/components/pages/index.vue';
import MediaPicker from '@/components/MediaPicker/MediaPicker.vue';
import { calculateMd5 } from "./tooler"

const mediaPicker = ref(null)

const tagStore = useTagStore()
const showForm = ref(false)
const currentTag = ref(null)
const tags = ref([])
const { pageData, pageList, loadPageData, createImage } = useDatabase()

const fetchResources = async (page = 1, limit = 10) => {
  const response = await uni.request({
    url: `http://localhost:4500/uni-record/resources?page=${page}&limit=${limit}`, // 替换成你的服务器地址
    method: 'GET'
  });
  console.log("response", response)
  const rs = response.data.data;
  tags.value = rs.resources
}

onMounted(() => {
  fetchResources()
})

function uploads(tempFilePaths, md5) {
  uni.uploadFile({
    url: 'http://localhost:4500/uni-record/resources/upload', // 替换成你的服务器地址
    filePath: tempFilePaths,
    name: 'file',
    formData: {
      'md5': md5
    },
    success: (uploadRes) => {
      console.log("uploadRes", uploadRes)
      const rs = JSON.parse(uploadRes.data)
      console.log(rs)
      tags.value.unshift(rs.data)
    }
  });
}

async function findByMd5(md5) {
  const response = await uni.request({
    url: `http://localhost:4500/uni-record/resources/${md5}`, // 替换成你的服务器地址
    method: 'GET'
  });

  console.log("Fetched resource:", response);
  if (response.data?.data?.path) {
    return response.data.data
  }
  return null
}
// 处理文件选择
const handleFileSelect = async (files) => {
  if (files && files.length > 0) {
    // 处理每个选中的文件
    for (const file of files) {
      const newFile = {
        ...file,
        file: file,
        md5: null
      }

      try {
        console.log("newFile", newFile)
        const md5 = await calculateMd5(file)
        const obj = await findByMd5(md5)
        if (obj) {
          console.log("obj", obj);
          fetchResources()
          return
        }
        // fileList.value[fileList.value.length-1].md5 = md5
        console.log("md5", md5)

        // 1.更新对应文件的 md5
        newFile.md5 = md5

        uploads(newFile.path, md5)

      } catch (error) {
        console.error('MD5计算失败:', error)
        uni.showToast({
          title: 'MD5计算失败',
          icon: 'none'
        })
      }
    }
  }
}

const showMediaPicker = () => {
  mediaPicker.value.open()
}

const handleEditTag = (tag) => {
  console.log("tag", tag)
}

const deleteTag = async (md5) => {
  const rs = await uni.request({
    url: `http://localhost:4500/uni-record/resources/${md5}`, // 替换成你的服务器地址
    method: 'DELETE'
  });
  console.log("rs", rs)
  uni.showToast({
    title: rs.data.message,
    icon: 'none'
  })
  fetchResources(); // 刷新列表
}

const handleDeleteTag = (tag) => {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除该标签吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          deleteTag(tag.md5)
        } catch (error) {
          uni.showToast({
            title: '删除失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

const handleCancelForm = () => {
  showForm.value = false
  currentTag.value = null
}

const handleSubmitTag = async (tagData) => {
  try {
    if (currentTag.value) {
      await tagStore.updateTag({ ...currentTag.value, ...tagData })
    } else {
      await tagStore.createTag(tagData)
    }
    showForm.value = false
    currentTag.value = null
  } catch (error) {
    console.error(error)
    uni.showToast({
      title: '保存失败',
      icon: 'none'
    })
  }
}

onMounted(async () => {
  fetchTagList(true)

})

// 添加分页相关变量
// const page = ref(1)
// const pageSize = ref(10)
const hasMore = ref(true)
const refreshing = ref(false)
const loading = ref(false)
const scrollHeight = ref(0)

// 添加获取标签列表方法
const fetchTagList = async (isRefresh = false) => {
  console.log('fetchTagList', isRefresh)
  if (isRefresh) {
    // page.value = 1
    pageData.page = 1
    hasMore.value = true
  }

  if (!hasMore.value || (loading.value && !isRefresh)) return

  loading.value = true
  try {
    await loadPageData()
  } catch (error) {
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
    if (isRefresh) {
      refreshing.value = false
    }
  }
}

// 添加刷新和加载更多方法
const handleRefresh = async () => {
  refreshing.value = true
  await fetchTagList(true)
}

</script>


<style lang="scss" scoped>
:deep(.uni-scroll-view-refresher) {
  background: none !important;
  margin-bottom: 20rpx;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32rpx;

  .header-title {
    font-size: 36rpx;
    font-weight: bold;
  }
}

.tags-list {

  .loading-state,
  .empty-state {
    // background: #fff;
    border-radius: 12rpx;
    padding: 48rpx;
    text-align: center;
    color: #909399;
    font-size: 28rpx;
  }

  .loading-state {
    background: transparent;
    margin: 20rpx 0;
  }

  .loading-more,
  .no-more {
    text-align: center;
    padding: 20rpx;
    color: #909399;
    font-size: 24rpx;
  }
}

.tags-content {
  display: flex;
  flex-wrap: wrap;
  gap: 16px; // 设置间距

  .tag-item {
    width: calc(50% - 8px); // 计算宽度以适应一行两列
    box-shadow: 0 4px 8px rgba(0, 0, 0, .1);
    border-radius: 8px;
    overflow: hidden;
    background-color: #fff;

    .tag-image {
      width: 100%;
      height: 200px; // 设置固定高度或其他合适的值

      image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .tag-actions {
      padding: 8px;
      display: flex;
      justify-content: space-around;
      background-color: #f9f9f9;

      button {
        flex: 1;
        margin: 0 4px;
        padding: 8px;
        border: none;
        border-radius: 4px;
        color: #fff;
        font-size: 14px;
        cursor: pointer;
      }
    }
  }
}
</style>